import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
    state: () => ({
        accessToken: localStorage.getItem('access_token') || '',
        refreshToken: localStorage.getItem('refresh_token') || ''
    }),
    actions: {
        setTokens(accessToken, refreshToken) {
            this.accessToken = accessToken
            this.refreshToken = refreshToken
            localStorage.setItem('access_token', accessToken)
            localStorage.setItem('refresh_token', refreshToken)
        },
        clearTokens() {
            this.accessToken = ''
            this.refreshToken = ''
            localStorage.removeItem('access_token')
            localStorage.removeItem('refresh_token')
        },
        // 刷新令牌方法（结合 /auth/refresh 接口）
        async refreshToken() {
            try {
                const res = await request.post('/auth/refresh', {
                    refresh_token: this.refreshToken
                })
                this.setTokens(res.data.access_token, this.refreshToken)
                return true
            } catch (error) {
                this.clearTokens()
                return false
            }
        }
    }
})